<!--
  * 分润提现表
  *
  * @Author:    zhoujk
  * @Date:      2025-01-23 04:08:27
-->
<template>
  <a-modal :title="'提现'" :width="600" :open="visibleFlag" @cancel="onClose" :maskClosable="false" :destroyOnClose="true">
    <a-form ref="formRef" :model="form" :rules="rules" layout="vertical">
      <group-title class="pb-0.5" :iconOptions="{ class: 'text-blue-400' }">基本信息</group-title>
      <div>
        <span>可用金额(元)：{{ formatToMoney(form.availableAmt / 100) }}</span>
      </div>
      <div>
        <span>提现起始金额(元)：{{ formatToMoney(form.drawStartAmt / 100) }}</span>
      </div>
      <a-form-item label="提现金额" name="drawAmt">
        <a-input-number
          style="width: 100%"
          :min="0"
          :max="form.availableAmt"
          v-model:value="form.drawAmt"
          placeholder="提现金额(元)"
          @change="handleChange"
        />
      </a-form-item>
      <div style="display: flex; flex-wrap: nowrap; justify-content: space-between">
        <span>手续费（1‰）：{{ form.fee }}￥</span><span>代扣费（7%）：{{ form.holdFee }}￥</span><span>实际到账金额：{{ form.actualAmt }}￥</span>
      </div>
      <a-row :gutter="16">
        <a-col class="gutter-row" :span="18">
          <a-form-item label="发票号" name="invoiceCode">
            <a-input style="width: 100%" v-model:value="form.invoiceCode" placeholder="请输入" />
          </a-form-item>
        </a-col>
        <a-col class="gutter-row" :span="6">
          <a-form-item label=" " :name="'invoiceUrl'">
            <a-upload
              v-model:file-list="form.invoiceUrl"
              name="invoiceUrl"
              :max-count="1"
              :custom-request="(file) => uploadFunc(file, 'form.invoiceUrl')"
              :accept="limitUpload.fileType.toString()"
              :before-upload="(file, fileList) => beforeUpload(file, fileList, 'invoiceUrl')"
              :headers="{
                authorization: 'authorization-text',
              }"
            >
              <a-button>
                <!-- <upload-outlined /> -->
                上传电子发票
              </a-button>
            </a-upload>
          </a-form-item>
        </a-col>
      </a-row>
      <a-form-item label="备注" name="remark">
        <a-textarea style="width: 100%" v-model:value="form.remark" :maxlength="60" placeholder="60个汉字" showCount />
      </a-form-item>
      <div v-if="debitCardFlag">
        <div>结算银行卡</div>
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="开户行" :name="['debitCardInsert', 'bankCode']">
              <CustomSelect
                v-model:value="form.debitCardInsert.bankCode"
                :placeholder="'请选择'"
                :api="bankApi.pageHead"
                queryParamKey="nameLike"
                :valueField="'code'"
                :labelField="'name'"
              />
            </a-form-item>
          </a-col>
          <!-- <a-col :span="12">
            <a-form-item label="开户行支行" name="bankBranchCode">
              <CustomSelect
                v-model:value="form.debitCardInsert.bankBranchCode"
                :placeholder="'请选择'"
                :api="bankApi.pageSub"
                queryParamKey="nameLike"
                :valueField="'interbankNo'"
                :labelField="'name'"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="开户行地区" name="bankAddressCode">
              <area-cascader v-model:value="form.debitCardInsert.bankAddressCode" />
            </a-form-item>
          </a-col> -->
          <a-col :span="12">
            <a-form-item label="开户人" :name="['debitCardInsert', 'accName']">
              <a-input v-model:value="form.debitCardInsert.accName" placeholder="请输入" />
            </a-form-item>
          </a-col>
          <!-- <a-col :span="12">
            <a-form-item label="结算账户类型" name="debitAccType">
              <SmartEnumSelect
                width="90%"
                v-model:value="form.debitCardInsert.debitAccType"
                enumName="DEBIT_CARD_ACC_TYPE_ENUM"
                placeholder="请选择"
              />
            </a-form-item>
          </a-col> -->
          <a-col :span="12">
            <a-form-item label="银行卡号" :name="['debitCardInsert', 'cardNo']">
              <a-input v-model:value="form.debitCardInsert.cardNo" placeholder="请输入" />
            </a-form-item>
          </a-col>
          <!-- <a-col :span="12">
            <a-form-item label="结算卡类型" name="cardType">
              <SmartEnumSelect width="90%" v-model:value="form.debitCardInsert.cardType" enumName="CARD_TYPE_ENUM" placeholder="请选择" />
            </a-form-item>
          </a-col> -->
          <a-col :span="12">
            <a-form-item label="法人身份证号码" :name="['debitCardInsert', 'legalPersonId']">
              <a-input v-model:value="form.debitCardInsert.legalPersonId" placeholder="请输入" />
            </a-form-item>
          </a-col>
          <!-- <a-col :span="12">
            <a-form-item label="是否为默认提现账户" name="defaultedFlag">
              <a-radio-group v-model:value="form.debitCardInsert.defaultedFlag">
                <a-radio :value="true">是</a-radio>
                <a-radio :value="false">否</a-radio>
              </a-radio-group>
            </a-form-item>
          </a-col> -->
        </a-row>
      </div>
    </a-form>

    <template #footer>
      <a-space>
        <a-button @click="onClose">取消</a-button>
        <a-button type="primary" @click="save">确认</a-button>
      </a-space>
    </template>
  </a-modal>
</template>
<script setup>
  import { reactive, ref, nextTick } from 'vue'
  import _ from 'lodash'
  import { message } from 'ant-design-vue'
  import { SmartLoading } from '/src/components/framework/smart-loading'
  import { profitDrawApi } from '/@/api/business/b-agent/profit/profit-draw/profit-draw-api'
  import { smartSentry } from '/src/lib/smart-sentry'
  import { debitCardApi } from '/@/api/business/b-agent/debit-card/debit-card-api.js'
  import SmartEnumSelect from '/@/components/framework/smart-enum-select/index.vue'
  import AreaCascader from '/@/components/business/b-operation/area-cascader/index.vue'
  import { exhibitionApi } from '/@/api/business/b-agent/exhibition/exhibition-api.js'
  import CustomSelect from '/@/components/business/comment/CustomSelect.vue'
  import { bankApi } from '/@/api/business/b-operation/bank/bank-api.js'
  import { formatToMoney, getObjValue, setObjValue, modifyFields, strToArr } from '/@/utils/common'
  import { myUpload } from '/@/utils/myUpload'

  // ------------------------ 事件 ------------------------

  const emits = defineEmits(['reloadList'])

  // ------------------------ 显示与隐藏 ------------------------
  // 是否显示
  const visibleFlag = ref(false)
  const debitCardFlag = ref(true)

  function show(rowData) {
    Object.assign(form, formDefault)
    if (rowData && !_.isEmpty(rowData)) {
      Object.assign(form, rowData)
    }

    // 查询默认结算卡信息
    debitCardApi.findDefault({ agentId: rowData.agentId }).then((res) => {
      debitCardFlag.value = !res.data
    })

    // 使用字典时把下面这注释修改成自己的字典字段 有多个字典字段就复制多份同理修改 不然打开表单时不显示字典初始值
    // if (form.status && form.status.length > 0) {
    //   form.status = form.status.map((e) => e.valueCode);
    // }
    visibleFlag.value = true
    nextTick(() => {
      formRef.value.clearValidate()
    })
  }

  function onClose() {
    Object.assign(form, formDefault)
    visibleFlag.value = false
  }

  // ------------------------ 表单 ------------------------

  // 组件ref
  const formRef = ref()

  const formDefault = {
    availableAmt: undefined, // 实时金额
    drawAmt: undefined, // 提现金额
    drawStartAmt: undefined, //提现起始金额
    fee: undefined, // 手续费
    holdFee: undefined, // 代扣费
    actualAmt: undefined, // 实际到账金额
    invoiceCode: undefined, // 发票号
    invoiceUrl: [], // 发票地址
    remark: undefined, // 备注
    debitCardInsert: {
      bankCode: undefined, // 开户行编号
      bankBranchCode: undefined, // 联行号
      bankAddressCode: undefined, // 开户行地区编码
      accName: undefined, // 开户人姓名
      debitAccType: undefined, // 结算账户类型
      cardNo: undefined, // 结算卡号
      cardType: undefined, // 结算卡类型
      legalPersonId: undefined, // 法人身份证号码
      defaultedFlag: true, // 是否为默认提现账户
    },
  }

  let form = reactive({ ...formDefault })

  const validate = async (rule, value) => {
    const val = (value * 100).toFixed(0)
    const min = form.drawStartAmt ? form.drawStartAmt : 0
    const max = form.availableAmt
    if (val < min) {
      return Promise.reject(new Error(`输入的值不能小于 ${formatToMoney(min / 100)}`))
    }
    if (val > max) {
      return Promise.reject(new Error(`输入的值不能大于 ${formatToMoney(max / 100)}`))
    }
    return Promise.resolve()
  }
  const rules = {
    invoiceCode: [{ required: true, message: '发票号 必填' }],
    drawAmt: [
      { required: true, message: '提现金额 必填' },
      { validator: validate, trigger: 'input' }, // 自定义校验规则
    ],
    debitCardInsert: {
      bankCode: [{ required: true, message: '开户行 必填' }],
      accName: [{ required: true, message: '开户人 必填' }],
      cardNo: [{ required: true, message: '银行卡号 必填' }],
      legalPersonId: [{ required: true, message: '法人身份证号码 必填' }],
    },
  }

  //校验表单
  const validateForm = async () => {
    let isValid = false
    try {
      await formRef.value.validate()
      isValid = true
    } catch (error) {
      message.warning(error.errorFields[0].errors)
      isValid = false
    }
    return isValid
  }
  ///* 上传附件 */

  const limitUpload = {
    fileType: ['.jpg', '.jpeg', '.png', '.bmp', '.gif', '.pdf'],
    fileSize: 5,
  }
  const beforeUpload = (file, fileList, type) => {
    // 校检文件类型
    if (limitUpload.fileType.length) {
      const fileExt = file.name.substring(file.name.lastIndexOf('.')).toLowerCase()
      const isTypeOk = limitUpload.fileType.includes(fileExt)
      if (!isTypeOk) {
        message.warning(`文件格式不正确, 请上传${limitUpload.fileType.toString().replace(/\./g, '').replace(/,/g, '、')}格式文件!`)
        return false || Upload.LIST_IGNORE
      }
    }

    // 校检文件大小
    if (limitUpload.fileSize) {
      const isLt = file.size / 1024 / 1024 < limitUpload.fileSize
      if (!isLt) {
        message.warning(`上传文件大小不能超过 ${limitUpload.fileSize} MB!`)
        return false || Upload.LIST_IGNORE
      }
    }

    return true
  }

  // 上传文件自定义的方法
  const uploadFunc = async (file, fieldName) => {
    // console.log('file==>', file)
    // 确保获取到文件对象
    const fileObj = file.file
    if (!fileObj) {
      return
    }
    const response = await myUpload(file)
    console.log('response==>', response)
    let arr = getObjValue(form, fieldName).map((item) => {
      if (item.uid === fileObj.uid) {
        message.success(`${fileObj.name} 上传成功`)
        return response
      }
      return item
    })
    setObjValue(form, fieldName, arr)
  }
  const imgField = ['invoiceUrl']
  // 图片初始化
  function imgInit(resData) {
    modifyFields(resData, imgField, (value, key) => {
      let val
      if (_.isEmpty(value)) return
      if (typeof value === 'string') {
        val = strToArr(value).map((item, index) => {
          return {
            uid: `db-file-${index}`,
            name: `${key}${index > 0 ? '_' + index : ''}`,
            status: 'done',
            url: item,
          }
        })
      }
      if (Array.isArray(value)) {
        val = value.map((e) => e.url).toString()
      }
      return val
    })
  }
  ///* 上传附件 */

  // 新建、编辑API
  async function save() {
    validateForm().then(async (isValid) => {
      if (isValid) {
        SmartLoading.show()
        try {
          const param = { ...form }
          if (!debitCardFlag.value) {
            param.debitCardInsert = undefined
          }
          param.drawAmt = (param.drawAmt * 100).toFixed(0)
          imgInit(param)
          await profitDrawApi.draw(param)
          message.success('操作成功')
          emits('reloadList')
          onClose()
        } catch (err) {
          console.error(err)

          smartSentry.captureError(err)
        } finally {
          SmartLoading.hide()
        }
      }
    })
  }

  const handleChange = (value) => {
    //保留两位小数并四舍五入
    form.fee = (value * 0.001).toFixed(2)
    form.holdFee = (value * 0.07).toFixed(2)
    form.actualAmt = (value - form.fee - form.holdFee).toFixed(2)
  }

  defineExpose({
    show,
  })
</script>
